package com.tanhua.server;

import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.exception.BusinessException;
import com.tanhua.model.User;
import com.tanhua.vo.ErrorResult;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    //注入SmsTemplate
    @Autowired
    private SmsTemplate template;
    //注入redisTemplate,
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @DubboReference
    private UserApi userApi;
    /*
        发送短信
    * */
    public void sendMsg(String phone){
        //产生一个六位数的验证码
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "666666";
        //将电话和验证码一起发到短信核心类，让第三方短信服务平台，将验证码发给用户手机
        //template.sendSms(phone,code);
        //将电话和验证码保存在redis方，设置过期时间为五分钟
        redisTemplate.opsForValue().set("CHECK_CODE" + phone,code, Duration.ofMinutes(5));
    }
        /*
        * 验证验证码
        * */
    public Map loginVerification(String phone, String code) throws BusinessException {
        //1.从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE" + phone);
        //2.将从redis中获取的验证跟前端传入的验证码进行校验
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //2.1验证码失效
            throw new BusinessException(ErrorResult.loginError());
        }
        //删除redis中验证
        redisTemplate.delete("CHECK_CODE" + phone);
        //通过号码查询用户是否存在
        User user = userApi.findByMoblie(phone);
        boolean isNew = false;
        if (user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;
        }
        //生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("mobile", phone);
        String token = JwtUtils.getToken(tokenMap);
        //构造返回值
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);
        return retMap;
      }
    }
